package cn.iocoder.yudao.module.system.dal.mysql.erp.warehousein;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehousein.vo.WarehouseInPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.operatelog.ErpOperateLogDO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehousein.WarehouseInDO;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

import static java.time.LocalDateTime.now;

/**
 * 入库单 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface WarehouseInMapper extends BaseMapperX<WarehouseInDO> {

    default PageResult<WarehouseInDO> selectPage(WarehouseInPageReqVO reqVO) {
        LambdaQueryWrapperX<WarehouseInDO> query = new LambdaQueryWrapperX<WarehouseInDO>()
                .eqIfPresent(WarehouseInDO::getWarehouseId, reqVO.getWarehouseId())
                .eqIfPresent(WarehouseInDO::getCustomerId, reqVO.getCustomerId())
                .betweenIfPresent(WarehouseInDO::getInWarehouseTime, reqVO.getInWarehouseTime())
                .betweenIfPresent(WarehouseInDO::getCreateTime, reqVO.getCreateTime())
                .inIfPresent(WarehouseInDO::getCustomerId, reqVO.getCustomerIds())
                .eqIfPresent(WarehouseInDO::getOperateBy, reqVO.getOperateBy());
        if(StrUtil.isNotBlank(reqVO.getWarehouse())){
            query.apply("(SELECT COUNT(0)>0 FROM erp_warehouse w WHERE w.id=t.customer_id and w.deleted=0 AND w.name LIKE '%"+reqVO.getWarehouse()+"%')");
        }
        if(StrUtil.isNotBlank(reqVO.getCustomer())){
            query.apply("(SELECT COUNT(0)>0 FROM system_users u WHERE u.id=t.customer_id and u.deleted=0 AND u.nickname LIKE '%"+reqVO.getCustomer()+"%')");
        }
        LocalDate startTime=reqVO.getStartTime();LocalDate endTime=reqVO.getEndTime();
        if(ObjectUtil.isNotEmpty(startTime)&&ObjectUtil.isNotEmpty(endTime)){
            query.between(WarehouseInDO::getInWarehouseTime,startTime.atStartOfDay(),endTime.atTime(23, 59, 59));
        }

        query.orderByDesc(WarehouseInDO::getId);
        return selectPage(reqVO, query);
    }

}